<?php 
class GoodsControl extends CommonControl{
        /**
         * 商品首页显示
         * @return [type] [description]
         */
    public function index()
    {
        $db = M("g_goods");
        $page = new Page($db->count());
        $this->assign("page", $page->show());
        $sql = "SELECT g.gname,g.gid,s.st_id,g.price,g.addtime,g.stock FROM hd_g_goods AS G JOIN hd_g_stock AS s
        ON g.gid=s.goods_gid GROUP BY g.gid LIMIT " . $page->limit(true);
        $goods = $db->query($sql);
        $this->assign("goods", $goods);
        $this->display();
    }

        /**
         * 商品添加
         */
    public function add()
    {
        if (IS_POST) {
            $db = M("g_goods");
            q("post.addtime", "strtotime");
            if (q("post.flag")) {
                $_POST['flag'] = implode(",", $_POST['flag']);
            }
            $goods_id = $db->add();
            //设置属性关联信息
            $this->setAttr($_POST['category_cid'], $goods_id);
            //设置规格
            $this->setSpec($_POST['category_cid'], $goods_id);
            //处理商品首页图片与列表页图片
            $this->setGoodsImages($goods_id);
            //处理商品内容页展示图片
            $this->setGoodsShowImages($goods_id);
            $this->success("添加商品成功", "index");
        } else {
            $this->assignCategory();
            $this->display();
        }     
    }

//编辑商品
    public function edit()
    {
        if (IS_POST) {
            $goods_id = q("post.gid", "intval");
            if (q("post.flag")) {
                $_POST['flag'] = implode(",", $_POST['flag']);
            }
            $db = M("g_goods");
            $db->save();
            //设置属性关联信息
            $this->setAttr($_POST['category_cid'], $goods_id);
            //设置规格
            $this->setSpec($_POST['category_cid'], $goods_id);
            //处理商品首页图片与列表页图片
            $this->setGoodsImages($goods_id);
            //处理商品内容页展示图片
            $this->setGoodsShowImages($goods_id);
            $this->success("修改商品成功", "index");
        } else {
            $gid = q("get.gid", "intval");
            if ($gid) {
                $db = M("g_goods");
                $field = $db->find($gid);
                $pics = $db->table("g_goods_pic")->where("goods_gid=" . $gid)->all();
                $this->assign("pics", $pics); //商品小、中、大图片
                $this->assign("field", $field);
                $this->assignCategory();
                $this->display();
            }
        }
    }

    /**
     * 删除商品
     * @return [type] [description]
     */
    public function del()
    {
        $db =M('g_goods');
        $gid = intval($_GET['gid']);
        $db->where('gid='.$gid)->del();
        $this->success("删除成功", "index");
    }

    //设置规格
    private function setSpec($cid, $goods_id)
    {
        $spec = q("post.spec");
        if (!$spec) return;
        //商品库存属性关联表
        $db = M("g_stock");
        //删除商品库存表数据
        $db->del("goods_gid=$goods_id");
        //删除库存与属性关联表中该商品的原有数据
        $db->table("g_stock_attr")->del("goods_gid=$goods_id");
        //添加库存表与库存规格关联表中的数据
        foreach ($spec as $s) {
            //如果价格或库存或货号为空，不插入库存表
            if (empty($s['price']) || empty($s['stock']) || empty($s['goods_sn'])) {
                continue;
            }
            //添加库存表数据goods_list表
            $stock_st_id = $db->add(array(
                "goods_gid" => $goods_id, //商品id
                "price" => $s['price'], //商品列表价格
                "stock" => $s['stock'], //库存
                "goods_sn" => $s['goods_sn'], //货号
            ));

            //库存与规格关联表数据 stock_attr 表
            foreach ($s["av_id"] as $av_id => $attr_value) {
                $data = array();
                $data["goods_gid"] = $goods_id; //商品id
                $data["attr_value_av_id"] = $av_id; //规格值id
                $data["stock_st_id"] = $stock_st_id; //库存表id
                $data["category_cid"] = $cid; //栏目cid
                $db->table("g_stock_attr")->add($data);
            }
        }
    }


    //分配栏目
    private function assignCategory()
    {
        $db = M("g_category");
        $category = $db->all();
        if (!$category) {
            $this->error("请先设置栏目", "Category/index");
        }
        $this->assign("category", Data::channelList($category, 0, '-'));
    }


    /**
     * 设置商品属性
     * @param $cid 栏目cid
     * @param $goods_id 商品id
     */
    private function setAttr($cid, $goods_id)
    {
        if ($attr = q("post.goods_attr")) {
            $db = M("g_goods_attr");
            //删除当前商品旧的属性信息
            $db->del("goods_gid=$goods_id");
            foreach ($attr as $k => $attr_value) {
                $data = array();
                $av_id = explode("_", $k);
                $data['category_cid'] = $cid;
                $data['goods_gid'] = $goods_id;
                $data['attr_value_av_id'] = $av_id[2];
                $data['attr_value'] = $attr_value;
                $db->add($data);
            }
        }
    }

    //商品内容页展示图片(局部放大图片)
    private function setGoodsShowImages($goods_id)
    {
        if (!empty($_FILES['goods_pic']['name'])) {
            //上传目录
            $uploadDir = './upload/goods/' . date("Ymd") . '/';
            $upload = new Upload($uploadDir);
            $uploadFile = $upload->upload('goods_pic');
            $image = new Image();
            $db = M("g_goods_pic");
            foreach ($uploadFile as $f) {
                $pathinfo = pathinfo($f['path']);
                $data = array("goods_gid" => $goods_id); //当前增加商品的主键
                $data['pic'] = $f['path']; //原图
                $data['small'] = $image->thumb($data['pic'], $pathinfo['filename'] . '_small.' . $pathinfo['extension'], C("pic_small_width"), C("pic_small_height"),
                    6, $uploadDir);
                $data['medium'] = $image->thumb($data['pic'], $pathinfo['filename'] . '_medium.' . $pathinfo['extension'], C("pic_medium_width"), C("pic_medium_height"),
                    6, $uploadDir);
                $db->add($data);
            }
        }
    }

    //处理商品首页图片与列表页图片
    private function setGoodsImages($goods_id)
    {
        if (!empty($_FILES['pic']['name'])) {
            $upload = new Upload('./upload/goods/');
            $uploadFile = $upload->upload('pic');
            //商品表中的图片数据
            $data = array("gid" => $goods_id); //当前增加商品的主键
            $data['pic'] = $uploadFile[0]['path']; //原图
            $image = new Image();
            $data['index_pic'] = $image->thumb($data['pic'],$uploadFile[0]['filename'] . '_index.' . $uploadFile[0]['ext'], C("index_pic_width"), C("index_pic_height"),
                1, './upload/goods');
            $data['list_pic'] = $image->thumb($data['pic'], $uploadFile[0]['filename'] . '_list.' . $uploadFile[0]['ext'], C("list_pic_width"), C("list_pic_height"),
                1, './upload/goods');
            $db = M("g_goods");
            $db->save($data);
            return true;
        }
    }

    //获得当前栏目的规格与属性
    public function getSpecAttr()
    {
        $cid = q("post.cid", "intval");
        if (!$cid) exit;
        //获得当前栏目的商品分类gtid
        $db = M("g_category");
        $categoryData = $db->field("goods_type_gt_id")->find($cid);
        //当前栏目的商品分类gtid
        $gtid = $categoryData["goods_type_gt_id"];
        //获得商品分类属性
        $db = K("AttrClassRelation");
        $data = array();
        $data['attr'] = $db->where("is_spec=0")->where("goods_type_gt_id=" . $gtid)->all();
        $data['spec'] = $db->where("is_spec=1")->where("goods_type_gt_id=" . $gtid)->all();
        $gid = q("post.gid", "intval");
        //添加商品不传递商品gid
        if ($gid) {
            //=======================编辑商品时获得当前商品的规格与属性=====================
            //-----------------------获得属性
            $data['edit_data']['attr'] = $db->table("g_goods_attr")->where("goods_gid=$gid")->all();
            //-----------------------获得规格
            //当前商品类型的所有规格分类
            //商品库存表
            $db = M("g_stock");
            //获得所有商品列表
            $stock = $db->all("goods_gid=$gid");
            if ($stock) {
                //查找库存商品的属性
                foreach ($stock as $n => $s) {
                    //获得商品所有规格
                    $stock[$n]["attr"] = $db->table("g_stock_attr")->where("stock_st_id={$s['st_id']}")->order("attr_value_av_id asc")->all();
                }
                $data['edit_data']['spec'] = $stock;
            }
        }
        $this->_ajax($data);
    }

    //删除商品内容页图片
    public function delPic()
    {
        $pic_id = q("get.pic_id", "intval");
        $db = M("g_goods_pic");
        $pics = $db->find($pic_id);
        unlink($pics["pic"]);
        unlink($pics["small"]);
        unlink($pics["medium"]);
        $db->del($pic_id);
        echo 1;
        exit;
    }











}
?>